package com.hmall.web;

import com.alibaba.fastjson.JSON;
import com.hmall.common.config.ItemFrignConfig;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.pojo.FilterDoc;
import com.hmall.pojo.ItemDoc;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ItemFrignConfig itemFrignConfig;

    //自动补全
    @GetMapping("/suggestion")
    public List<String> suggestion(@RequestParam("key") String key) throws IOException {
        SearchRequest request = new SearchRequest("hmall1");
        request.source().suggest(new SuggestBuilder()
                .addSuggestion("suggestions", SuggestBuilders
                        .completionSuggestion("suggestion").prefix(key).skipDuplicates(true).size(10)));
//        发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//        j解析
        Suggest suggest = response.getSuggest();
        CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
        List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
        ArrayList<String> strings = new ArrayList<>();
        for (CompletionSuggestion.Entry.Option option : options) {
            String s = option.getText().toString();
            strings.add(s);
        }
        return strings;
    }

    //    过滤聚合
    @PostMapping("/filters")
    public Map<String, List<String>> filtersController(@RequestBody FilterDoc filterDoc) throws IOException {
        SearchRequest request = new SearchRequest("hmall1");
        request.source().size(0);
//
        request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(100));
        request.source().aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(100));
//        解析结果
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        Aggregations aggregations = response.getAggregations();
        Terms brandAgg = aggregations.get("brandAgg");
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        ArrayList<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            list.add(keyAsString);
        }
        Terms categoryAgg = aggregations.get("categoryAgg");
        List<? extends Terms.Bucket> buckets1 = categoryAgg.getBuckets();
        ArrayList<String> list1 = new ArrayList<>();
        for (Terms.Bucket bucket1 : buckets1) {
            String keyAsString1 = bucket1.getKeyAsString();
            list1.add(keyAsString1);
        }
        HashMap<String, List<String>> map = new HashMap<>();
        map.put("category", list1);
        map.put("brand", list);
        return map;
    }

    //    基本搜索功能
    @PostMapping("/list")
    public PageDTO<ItemDoc> listPageController(@RequestBody FilterDoc filterDoc) throws IOException {
        SearchRequest request = new SearchRequest("hmall1");
        String key = filterDoc.getKey();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(key==null||"".equals(key)){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }
//       分类条件
        if(filterDoc.getCategory()!=null&&!filterDoc.getCategory().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("category",filterDoc.getCategory()));
        }
//        品牌
        if(filterDoc.getBrand()!=null&&!filterDoc.getBrand().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("brand",filterDoc.getBrand()));
        }
//        价格
        if(filterDoc.getMaxPrice()!=null&&filterDoc.getMaxPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(filterDoc.getMinPrice()).lte(filterDoc.getMaxPrice()));
        }
//        分页
        request.source().from(filterDoc.getPage()).size(filterDoc.getSize());
        request.source().query(boolQuery);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//        解析
        SearchHits hits = response.getHits();
//        总条数
        long value = hits.getTotalHits().value;
        SearchHit[] hits1 = hits.getHits();
        ArrayList<ItemDoc> list = new ArrayList<>();
        for (SearchHit hit : hits1) {
            String json = hit.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
            list.add(itemDoc);
        }
      return  new PageDTO<>(value,list);
    }
}
